package com.hyk.commonLib.common.utils;

import android.content.Context;
import android.os.PowerManager;

import java.util.HashMap;

public class WakeLockUtils {
    private static final HashMap<String, WakeLockUtils> holderMap = new HashMap<>();

    private final PowerManager.WakeLock mWakeLock;

    private WakeLockUtils(String taskName, int levelAndFlags) {
        PowerManager mPowerManager = (PowerManager) AppUtils.getAppContext().getSystemService(Context.POWER_SERVICE);
        mWakeLock = mPowerManager.newWakeLock(levelAndFlags, "commonLib:" + taskName);
    }

    public static WakeLockUtils getSingleton(String taskName, int levelAndFlags) {
        String key = "taskName:" + taskName + "_levelAndFlags:" + levelAndFlags;
        if (!holderMap.containsKey(key)) {
            synchronized (WakeLockUtils.class) {
                if (!holderMap.containsKey(key)) {
                    holderMap.put(key, new WakeLockUtils(taskName, levelAndFlags));
                }
            }
        }
        return holderMap.get(key);
    }

    public static WakeLockUtils getSingleton(String taskName) {
        return getSingleton(taskName, PowerManager.PARTIAL_WAKE_LOCK);
    }

    public synchronized void acquireWakeLock() {
        if (mWakeLock.isHeld()) releaseWakeLock();
        mWakeLock.acquire();
    }

    public synchronized void releaseWakeLock() {
        if (mWakeLock.isHeld()) mWakeLock.release();
    }
}
